package com.d3works.apps.bpm.script;

import com.d3works.apps.bpm.context.WkfContextHelper;
import com.d3works.apps.tool.context.FullContext;
import com.d3works.auth.AuthUtils;
import com.d3works.inject.Beans;
import com.d3works.meta.db.repo.MetaJsonRecordRepository;
import com.d3works.script.GroovyScriptHelper;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;

public class D3worksScriptEngine extends GroovyScriptEngineImpl {

  private volatile D3worksScriptEngineFactory factory;

  D3worksScriptEngine(D3worksScriptEngineFactory factory) {
    super();
    this.factory = factory;
  }

  @Override
  public Object eval(String script, ScriptContext ctx) {
    Bindings bindings = ctx.getBindings(ctx.getScopes().get(0));
    bindings.put("$json", Beans.get(MetaJsonRecordRepository.class));
    bindings.put("$ctx", WkfContextHelper.class);
    bindings.put("$beans", Beans.class);
    bindings.put("__user__", new FullContext(AuthUtils.getUser()));
    return new GroovyScriptHelper(bindings).eval(script);
  }

  @Override
  public CompiledScript compile(String scriptSource) throws ScriptException {
    return null;
  }

  public ScriptEngineFactory getFactory() {
    if (factory == null) {
      synchronized (this) {
        if (factory == null) {
          factory = new D3worksScriptEngineFactory();
        }
      }
    }
    return factory;
  }
}
